<?php

class Country_IndexController extends Core_Controller_Action_Standard
{
  
  public function indexAction()
  {
    $this->view->someVar = 'someVal';
  }
  
  public function suggestAction(){
    
    $viewer = Engine_Api::_()->user()->getViewer();
    $country_id = $this->_getParam('country_id', 0);
    $country = Engine_Api::_()->getItem('country', $country_id);
  //var_dump($country);die;
    if( !$viewer->getIdentity() || !$country->getIdentity() ) {
      $data = null;
    } else {
      $data = array();
      $table = Engine_Api::_()->getItemTable('user');
      $select = $table->select();      
      //$select = Engine_Api::_()->user()->getViewer()->membership()->getMembersObjectSelect();

      if( $this->_getParam('includeSelf', false) ) {
        $data[] = array(
          'type' => 'user',
          'id' => $viewer->getIdentity(),
          'guid' => $viewer->getGuid(),
          'label' => $viewer->getTitle() . ' (you)',
          'photo' => $this->view->itemPhoto($viewer, 'thumb.icon'),
          'url' => $viewer->getHref(),
        );
      }

      if( 0 < ($limit = (int) $this->_getParam('limit', 10)) ) {
        $select->limit($limit);
      }

      if( null !== ($text = $this->_getParam('search', $this->_getParam('value'))) ) {
        $select->where('`'.$table->info('name').'`.`displayname` LIKE ?', '%'. $text .'%');
        
        $countrymemberTb = Engine_Api::_()->getDbTable('countrymembers', 'country');
        $list_member = $countrymemberTb->getListMemberIds($viewer->getIdentity(), $country_id);
       //print_r($list_member);die; 
        if(count($list_member) > 0)
            $select->where('user_id not in (?)', $list_member);
      }
   // echo $select;die;  
      $ids = array();
      foreach( $select->getTable()->fetchAll($select) as $friend ) {
        $data[] = array(
          'type'  => 'user',
          'id'    => $friend->getIdentity(),
          'guid'  => $friend->getGuid(),
          'label' => $friend->getTitle(),
          'photo' => $this->view->itemPhoto($friend, 'thumb.icon'),
          'url'   => $friend->getHref(),
        );
        $ids[] = $friend->getIdentity();
        $friend_data[$friend->getIdentity()] = $friend->getTitle();
      }

      // first get friend lists created by the user
      $listTable = Engine_Api::_()->getItemTable('user_list');
      $lists = $listTable->fetchAll($listTable->select()->where('owner_id = ?', $viewer->getIdentity()));
      $listIds = array();
      foreach( $lists as $list ) {
        $listIds[] = $list->list_id;
        $listArray[$list->list_id] = $list->title;
      }

      // check if user has friend lists
      if( $listIds ) {
        // get list of friend list + friends in the list
        $listItemTable = Engine_Api::_()->getItemTable('user_list_item');
        $uName = Engine_Api::_()->getDbtable('users', 'user')->info('name');
        $iName  = $listItemTable->info('name');

        $listItemSelect = $listItemTable->select()
          ->setIntegrityCheck(false)
          ->from($iName, array($iName.'.listitem_id', $iName.'.list_id', $iName.'.child_id',$uName.'.displayname'))
          ->joinLeft($uName, "$iName.child_id = $uName.user_id")
          //->group("$iName.child_id")
          ->where('list_id IN(?)', $listIds);

        $listItems = $listItemTable->fetchAll($listItemSelect);

        $listsByUser = array();
        foreach( $listItems as $listItem ) {
          $listsByUser[$listItem->list_id][$listItem->user_id]= $listItem->displayname ;
        }
        
        foreach ($listArray as $key => $value){
          if (!empty($listsByUser[$key])){
            $data[] = array(
              'type' => 'list',
              'friends' => $listsByUser[$key],
              'label' => $value,
            );
          }
        }
      }
    }

    //print_r($data);die;
    if( $this->_getParam('sendNow', true) ) {
      return $this->_helper->json($data);
    } else {
      $this->_helper->viewRenderer->setNoRender(true);
      $data = Zend_Json::encode($data);
      
    
      $this->getResponse()->setBody($data);
    }
  
  }
  
  public function invitebakAction(){
    $country_id = $this->_getParam('id',0);
    $this->view->country_id = $country_id;
    
    //if( !$this->_helper->requireUser()->isValid() ) return;
    //if( !$this->_helper->requireSubject('country')->isValid() ) return;
    // @todo auth

    // Prepare data
    $viewer = Engine_Api::_()->user()->getViewer();
    $this->view->country = $country = Engine_Api::_()->getItem('country', $country_id);
    $this->view->friends = $friends = $viewer->membership()->getMembers();
    
    //print_r($friends);die;

    // Prepare form
    $this->view->form = $form = new Country_Form_Invite();
/*
    $count = 0;
    foreach( $friends as $friend )
    {
      if( $country->isMember($friend->getIdentity()) ) continue;
      $form->users->addMultiOption($friend->getIdentity(), $friend->getTitle());
      $count++;
    }
    $this->view->count = $count;

    // throw notice if count = 0
    if( $count == 0 ) {
      return $this->_forward('success', 'utility', 'core', array(
      'messages' => array(Zend_Registry::get('Zend_Translate')->_('You have no friends you can invite.')),
      'layout' => 'default-simple',
      'parentRefresh' => true,
      ));
    }
*/

    // Get params
    $multi = $this->_getParam('multi');
    $to = $this->_getParam('to');
    $viewer = Engine_Api::_()->user()->getViewer();
    $toObject = null;

    // Build
    $isPopulated = false;
    if( !empty($to) && (empty($multi) || $multi == 'user') ) {
      $multi = null;
      // Prepopulate user
      $toUser = Engine_Api::_()->getItem('user', $to);
      $isMsgable = ( 'friends' != Engine_Api::_()->authorization()->getPermission($viewer, 'messages', 'auth') ||
          $viewer->membership()->isMember($toUser) );
      if( $toUser instanceof User_Model_User &&
          (!$viewer->isBlockedBy($toUser) && !$toUser->isBlockedBy($viewer)) &&
          isset($toUser->user_id) &&
          $isMsgable ) {
        $this->view->toObject = $toObject = $toUser;
        $form->toValues->setValue($toUser->getGuid());
        $isPopulated = true;
      } else {
        $multi = null;
        $to = null;
      }
    } else if( !empty($to) && !empty($multi) ) {
      // Prepopulate group/event/etc
      $item = Engine_Api::_()->getItem($multi, $to);
      // Potential point of failure if primary key column is something other
      // than $multi . '_id'
      $item_id = $multi . '_id';
      if( $item instanceof Core_Model_Item_Abstract &&
          isset($item->$item_id) && (
            $item->isOwner($viewer) ||
            $item->authorization()->isAllowed($viewer, 'edit')
          )) {
        $this->view->toObject = $toObject = $item;
        $form->toValues->setValue($item->getGuid());
        $isPopulated = true;
      } else {
        $multi = null;
        $to = null;
      }
    }
    $this->view->isPopulated = $isPopulated;

    // Build normal
    if( !$isPopulated ) {
      // Apparently this is using AJAX now?
//      $friends = $viewer->membership()->getMembers();
//      $data = array();
//      foreach( $friends as $friend ) {
//        $data[] = array(
//          'label' => $friend->getTitle(),
//          'id' => $friend->getIdentity(),
//          'photo' => $this->view->itemPhoto($friend, 'thumb.icon'),
//        );
//      }
//      $this->view->friends = Zend_Json::encode($data);
    }
    
    // Assign the composing stuff
    $composePartials = array();
    foreach( Zend_Registry::get('Engine_Manifest') as $data ) {
      if( empty($data['composer']) ) {
        continue;
      }
      foreach( $data['composer'] as $type => $config ) {
        // is the current user has "create" privileges for the current plugin
    /*    
        $isAllowed = Engine_Api::_()
            ->authorization()
            ->isAllowed($config['auth'][0], null, $config['auth'][1]);
            
        if( !empty($config['auth']) && !$isAllowed ) {
          continue;
        }
        
*/
        $composePartials[] = $config['script'];
      }
    }
    $this->view->composePartials = $composePartials;
    // $this->view->composePartials = $composePartials;

    // Get config
    $this->view->maxRecipients = $maxRecipients = 10;
    // Not posting
    if( !$this->getRequest()->isPost() )
    {
      return;
    }

    if( !$form->isValid($this->getRequest()->getPost()) )
    {
      return;
    }

$values = $form->getValues();
$list_user_ids = array();
$list_user_ids = explode(',', $values['toValues']);
//print_r($values);die;
    // Process
    $table = $country->getTable();
    $db = $table->getAdapter();
    $countrymemberTb = Engine_Api::_()->getDbtable('countrymembers', 'country');
    $db->beginTransaction();

    try
    {
      //$usersIds = $form->getValue('users');
      
      $notifyApi = Engine_Api::_()->getDbtable('notifications', 'activity');
      foreach( $list_user_ids as $item_id )
      {
        
        $friend = Engine_Api::_()->getItem('user', $item_id);
        $friend_id = $friend->user_id;
        $countrymemberTb->inviteMember1($item_id, $country_id);

        $notifyApi->addNotification($friend, $viewer, $country, 'country_invite');
        
      }


      $db->commit();
    }

    catch( Exception $e )
    {
      $db->rollBack();
      throw $e;
    }
    
    return $this->_forward('success', 'utility', 'core', array(
      'messages' => array(Zend_Registry::get('Zend_Translate')->_('Members invited')),
      'layout' => 'default-simple',
      'parentRefresh' => true,
    ));
  
  }
  
  public function viewAction(){
    $id = $this->_getParam('id',0);
    $viewer = Engine_Api::_()->user()->getViewer();
    if (!empty($id)){
        $country = Engine_Api::_()->getItem('country_country',$id);
    }
    
    if (!$country){
        return $this->_forward('notfound', 'error', 'core');
    }

    if ( !$this->_helper->requireUser()->isValid() ) {
        return $this->_forward('requireauth', 'error', 'core');
    }
    
    if ( !Engine_Api::_()->authorization()->isAllowed($country,$viewer,'view') ){
        //return $this->_forward('requireauth', 'error', 'core');
    }
    
    if ( $country->isBlock($viewer)){
        return $this->_forward('requireauth', 'error', 'core');
    }
    
    if( !Engine_Api::_()->core()->hasSubject() ) {
       Engine_Api::_()->core()->setSubject($country);
    }
    
    $listingtype_id = $this->_getParam('listingtype_id', null);
    if ($listingtype_id != -1 && !empty($listingtype_id)) {
      Engine_Api::_()->sitereview()->setListingTypeInRegistry($listingtype_id);
      $this->_listingType = Zend_Registry::get('listingtypeArray' . $listingtype_id);
      Zend_Registry::isRegistered('sitereviewGetListingType') ? $sitereviewGetListingType = true : $this->_setParam('listing_id', 0);

      //AUTHORIZATION CHECK
      /*if ($this->_getParam('action', null) != 'categories')
        if (!$this->_helper->requireAuth()->setAuthParams('sitereview_listing', null, "view_listtype_$listingtype_id")->isValid())
          return;
		  */
    }
   
    $params['listing_type_title'] = $this->_getParam('title_plural');
    
    $this->_helper->content
        ->setNoRender()
        ->setEnabled()
        ;
  }
  
  
  public function viewMediaAction()
  {
    
    $country_id = $this->_getParam('cid',0);
    if( empty($country_id)) {
       return $this->_helper->content
        ->setNoRender()
        ->setEnabled()
        ;
    }
    $country = Engine_Api::_()->getItem('country',$country_id);
    if (!$country) {
        return $this->_helper->content
        ->setNoRender()
        ->setEnabled()
        ;
    }
    
    if( !Engine_Api::_()->core()->hasSubject() ) {
       Engine_Api::_()->core()->setSubject($country);
    }
    $this->view->subject = $country;
    // Prepare params
    $this->view->page = $page = $this->_getParam('page',1);

    $introduceMedia = Engine_Api::_()->getDbTable('introducemedias','country') ;
        
    $select = $introduceMedia->select()
                             ->where('country_id = ?', $country_id);
                                    
    // Prepare data
    $this->view->paginator =  $paginator = Zend_Paginator::factory($select);
    $paginator->setItemCountPerPage( 25);
    $paginator->setCurrentPageNumber($page);

    // Do other stuff
    $this->view->mine = true;
    $this->view->canEdit = false;
    
  }
  
  public function addCountriesAction(){
        $temp = array(

"Central African Republic"

, 

"Cameroon"

, 

"Ghana"

, 

"Sierra Leone"

, 

"Mauritania"

, 

"Western Sahara"

, 

"Morocco"

, 

"Algeria"

, 

"Western Sahara"

, 

"Mauritania"

, 

"Senegal"

, 

"Mali"

, 

"Guinea"

, 

"Guinea-Bissau"

, 

"Senegal"

, 

"Gambia"

, 

"Senegal"

, 

"Guinea-Bissau"

, 

"Senegal"

, 

"Guinea-Bissau"

, 

"Guinea"

, 

"Sierra Leone"

, 

"Guinea"

, 

"Liberia"

, 

"Guinea"

, 

"Ivory Coast"

, 

"Guinea"

, 

"Liberia"

, 

"Sierra Leone"

, 

"Guinea"

, 

"Ivory Coast"

, 

"Ghana"

, 

"Ivory Coast"

, 

"Ghana"

, 

"Burkina Faso"

, 

"Benin"

, 

"Togo"

, 

"Benin"

, 

"Nigeria"

, 

"Niger"

, 

"Algeria"

, 

"Tunisia"

, 

"Libya"

, 

"Chad"

, 

"Niger"

, 

"Chad"

, 

"Sudan"

, 

"Egypt"

, 

"Sudan"

, 

"Eritrea"

, 

"Ethiopia"

, 

"Somalia"

, 

"Ethiopia"

, 

"Somalia"

, 

"Kenya"

, 

"Uganda"

, 

"Zaire"

, 

"Zambia"

, 

"Zaire"

, 

"Zambia"

, 

"Zaire"

, 

"Zambia"

, 

"Zaire"

, 

"Zambia"

, 

"Tanzania"

, 

"Kenya"

, 

"Uganda"

, 

"Tanzania"

, 

"Mozambique"

, 

"Malawi"

, 

"Mozambique"

, 

"Zambia"

, 

"Malawi"

, 

"Zambia"

, 

"Zaire"

, 

"Zambia"

, 

"Angola"

, 

"Namibia"

, 

"Botswana"

, 

"Zimbabwe"

, 

"Mozambique"

, 

"South Africa"

, 

"South Africa"

, 

"Lesotho"

, 

"South Africa"

, 

"Lesotho"

, 

"South Africa"

, 

"Madagascar"

, 

"South Africa"

, 

"Namibia"

, 

"Angola"

, 

"Zaire"

, 

"Congo"

, 

"Gabon"

, 

"Equatorial Guinea"

, 

"Cameroon"

, 

"Nigeria"

, 

"Togo"

, 

"Ivory Coast"

, 

"Burkina Faso"

, 

"Ivory Coast"

, 

"Ghana"

, 

"Togo"

, 

"Benin"

, 

"Nigeria"

, 

"Benin"

, 

"Togo"

, 

"Ghana"

, 

"Burkina Faso"

, 

"Mali"

, 

"Guinea"

, 

"Sierra Leone"

, 

"Liberia"

, 

"Liberia"

, 

"Sierra Leone"

, 

"Guinea"

, 

"Guinea"

, 

"Guinea-Bissau"

, 

"Senegal"

, 

"Mauritania"

, 

"Western Sahara"

, 

"Mauritania"

, 

"Mali"

, 

"Niger"

, 

"Nigeria"

, 

"Cameroon"

, 

"Central African Republic"

, 

"Congo"

, 

"Zaire"

, 

"Zambia"

, 

"Zaire"

, 

"Zambia"

, 

"Malawi"

, 

"Mozambique"

, 

"Madagascar"

, 

"Mozambique"

, 

"Tanzania"

, 

"Kenya"

, 

"Somalia"

, 

"Ethiopia"

, 

"Sudan"

, 

"Egypt"

, 

"Libya"

, 

"Algeria"

, 

"Tunisia"

, 

"Algeria"

, 

"Morocco"

, 

"Western Sahara"

, 

"Mauritania"

, 

"Senegal"

, 

"Guinea-Bissau"

, 

"Guinea"

, 

"Ivory Coast"

, 

"Liberia"

, 

"Sierra Leone"

, 

"Guinea"

, 

"Ivory Coast"

, 

"Burkina Faso"

, 

"Togo"

, 

"Ghana"

, 

"Togo"

, 

"Ghana"

, 

"Togo"

, 

"Benin"

, 

"Niger"

, 

"Nigeria"

, 

"Niger"

, 

"Algeria"

, 

"Niger"

, 

"Chad"

, 

"Niger"

, 

"Nigeria"

, 

"Cameroon"

, 

"Central African Republic"

, 

"Zaire"

, 

"Congo"

, 

"Gabon"

, 

"Equatorial Guinea"

, 

"Cameroon"

, 

"Equatorial Guinea"

, 

"Gabon"

, 

"Congo"

, 

"Cameroon"

, 

"Congo"

, 

"Zaire"

, 

"Tanzania"

, 

"Uganda"

, 

"Kenya"

, 

"Tanzania"

, 

"Mozambique"

, 

"Malawi"

, 

"Mozambique"

, 

"Zimbabwe"

, 

"Mozambique"

, 

"Zambia"

, 

"Zimbabwe"

, 

"South Africa"

, 

"Botswana"

, 

"Namibia"

, 

"Angola"

, 

"Angola"

, 

"Zaire"

, 

"Angola"

, 

"Zaire"

, 

"Zambia"

, 

"Zambia"

, 

"Botswana"

, 

"Namibia"

);      $Ctable = Engine_Api::_()->getDbtable('countries','country');
        foreach ($temp as $item){
            $row = $Ctable->createRow();
            $row->title = $item;
            $row->owner_id = 1;
            $row->description = $item;
            $row->save();
        }      
  }
  
  public function fieldsAction(){
     $viewer = Engine_Api::_()->user()->getViewer();
     $subject = null;
     if( Engine_Api::_()->core()->hasSubject() ) {
       // Get subject
       $subject = Engine_Api::_()->core()->getSubject();
      
     }
     $this->_helper->content
        ->setNoRender()
        ->setEnabled()
        ;
     
     
     
     
  }
  
   public function allfieldsAction(){
     $viewer = Engine_Api::_()->user()->getViewer();
     
     $this->_helper->content
        ->setNoRender()
        ->setEnabled()
        ;
     
     
     
     
  }
  
  public function leaveAction(){
     if (!$this->getRequest()->isPost()){
        $form = new Country_Form_Delete();
        $form->setTitle('Leave Country');
        $form->setDescription('Could you want to leave this country?');
        $form->getElement('submit')->setLabel('Yes');
        $form->getElement('cancel')->setLabel('No');
        $this->view->form = $form;
        return;
     }
     $viewer = Engine_Api::_()->user()->getViewer();
     $country_id = $this->_getParam('id',0);
     
     if (!$viewer || !$viewer->user_id  || !$country_id){
        return $this->_forward('success', 'utility', 'core', array(
                    'smoothboxClose' => 1000,
                    'messages' => array('Can not found this country.')
        ));
     }
     
     $memberTable = Engine_Api::_()->getDbtable('countrymembers','country');
     $memberTable->leaveMember($viewer->user_id,$country_id);
	 
	//add notification
	 $country = Engine_Api::_()->getItem('country', $country_id);
	 if($country){
		//get managers and admin list
		$managers = Engine_Api::_()->getDbtable('managers','country')->getUserManagerId($country_id);
		$userAdmins = Engine_Api::_()->getItemTable('user')->fetchAll(Engine_Api::_()->getItemTable('user')->select()->where('level_id < 4'));
		$admins = array();
		$notifyApi = Engine_Api::_()->getDbtable('notifications', 'activity');
		foreach($userAdmins as $user){
			$notifyApi->addNotification($user, $viewer, $country, 'left_country', array(
				  'label' => $country->title
				));
			$admins[] = $user->user_id;	
		}
		foreach($managers as $m){
			if(in_array($m, $admins)) continue;
			$user = Engine_Api::_()->getItem('user', $m);
			if($user){
				$notifyApi->addNotification($user, $viewer, $country, 'left_country', array(
				  'label' => $country->title
				));
			}
		}
	}
	
     return $this->_forward('success', 'utility', 'core', array(
                    'smoothboxClose' => 1000,
                    'parentRefresh'=> 1000,
                    'messages' => array('You has leave to country success')
     ));
  }
  public function rejectAction(){
     if (!$this->getRequest()->isPost()){
        $form = new Country_Form_Delete();
        $form->setTitle('Reject Join Invitation');
        $form->setDescription('Could you want to reject this invitation?');
        $form->getElement('submit')->setLabel('Yes');
        $form->getElement('cancel')->setLabel('No');
        $this->view->form = $form;
        return;
     }
     $viewer = Engine_Api::_()->user()->getViewer();
     $country_id = $this->_getParam('id',0);
     
     if (!$viewer || !$viewer->user_id  || !$country_id){
        return $this->_forward('success', 'utility', 'core', array(
                    'smoothboxClose' => 1000,
                    'messages' => array('Can not found this country.')
        ));
     }
     
     $memberTable = Engine_Api::_()->getDbtable('countrymembers','country');
     $memberTable->leaveMember($viewer->user_id,$country_id);
     
     return $this->_forward('success', 'utility', 'core', array(
                    'smoothboxClose' => 1000,
                    'parentRefresh'=> 1000,
                    'messages' => array('Successful')
     ));
  }
  public function joinAction(){	
    if (!$this->getRequest()->isPost()){
        $form = new Country_Form_Delete();
        $form->setTitle('Join Country');
        $form->setDescription('Could you want to Join this country?');
        $form->getElement('submit')->setLabel('Yes');
        $form->getElement('cancel')->setLabel('No');
        $this->view->form = $form;
        return;
     }
     $viewer = Engine_Api::_()->user()->getViewer();
     $country_id = $this->_getParam('id',0);
     
     if (!$viewer || !$viewer->user_id  || !$country_id){
        return $this->_forward('success', 'utility', 'core', array(
                    'smoothboxClose' => 1000,
                    'messages' => array('Can not found this country.')
        ));
     }
     
     $memberTable = Engine_Api::_()->getDbtable('countrymembers','country');
     $memberTable->joinMember($viewer->user_id,$country_id);
	 
	//add notification
	 $country = Engine_Api::_()->getItem('country', $country_id);
	 if($country){
		//get managers and admin list
		$managers = Engine_Api::_()->getDbtable('managers','country')->getUserManagerId($country_id);
		$userAdmins = Engine_Api::_()->getItemTable('user')->fetchAll(Engine_Api::_()->getItemTable('user')->select()->where('level_id < 4'));
		$admins = array();
		$notifyApi = Engine_Api::_()->getDbtable('notifications', 'activity');
		foreach($userAdmins as $user){
			$notifyApi->addNotification($user, $viewer, $country, 'joined_country', array(
				  'label' => $country->title
				));
			$admins[] = $user->user_id;	
		}
		foreach($managers as $m){
			if(in_array($m, $admins)) continue;
			$user = Engine_Api::_()->getItem('user', $m);
			if($user){
				$notifyApi->addNotification($user, $viewer, $country, 'joined_country', array(
				  'label' => $country->title
				));
			}
		}
	}
	 
     $this->_forward('success', 'utility', 'core', array(
                    'smoothboxClose' => 1000,
                    'parentRefresh'=> 1000,
                    'messages' => array('You have joined to country success')
     ));
  }
  
  public function rateAction()
  {
        $viewer = Engine_Api::_()->user()->getViewer();
        $user_id = $viewer->getIdentity();
        
        $rating = $this->_getParam('rating');
        $country_id =  $this->_getParam('country_id');
    
        
        $table = Engine_Api::_()->getDbtable('ratings', 'country');
        $db = $table->getAdapter();
        $db->beginTransaction();
    
        try
        {
          Engine_Api::_()->country()->setRating($country_id, $user_id, $rating);
             
          $country = Engine_Api::_()->getItem('country', $country_id);
          $country->rating = Engine_Api::_()->country()->getRating($country->getIdentity());
          $country->save();
    
          $db->commit();
        }
    
        catch( Exception $e )
        {
          $db->rollBack();
          throw $e;
        }
    
        $total = Engine_Api::_()->country()->ratingCount($country->getIdentity());
    
        $data = array();
        $data[] = array(
          'total' => $total,
          'rating' => $rating,
        );
        return $this->_helper->json($data);
        $data = Zend_Json::encode($data);
        $this->getResponse()->setBody($data);
    }
	public function voteAction()
  {
        $viewer = Engine_Api::_()->user()->getViewer();
        $user_id = $viewer->getIdentity();
        
       	$vote  = $this->_getParam('vote');
        $country_id =  $this->_getParam('country_id');
    	$option =  $this->_getParam('option_id');
        
        $table = Engine_Api::_()->getDbtable('voteresults', 'country');
        $votetable = Engine_Api::_()->getDbtable('vote', 'country');
        $select = $table->select()
          			->where('voteoption_id = ?', $option)
          			->where('country_id = ?', $country_id);
        $db = $table->getAdapter();
        $db->beginTransaction();
    
        try
        {  				
          $voteresults = $table->fetchRow($select);
          			    
          if($voteresults){
          	//check if this user had voted
          	$selectv = $votetable->select()
          				->where('voteoption_id = ?', $option)
          			    ->where('country_id = ?', $country_id)
          				->where('user_id = ?', $user_id);
          	$voteData = $votetable->fetchRow($selectv);
          	
          	//update for voting 
          	if($voteData){
          		if($vote){
          			if($voteData->is_like == 0){
	          			$voteresults->total_like++;
	          			$voteresults->total_unlike--; 
          			}	         			
          		}else{
          			if($voteData->is_like == 1){
	          			$voteresults->total_like--;
	          			$voteresults->total_unlike++;
          			}	
          		}
          		$voteresults->save();
          	}else{
          		if($vote){
          			$voteresults->total_like++;
          		}else{
          			$voteresults->total_unlike++;
          		}
          		$voteresults->save();
          	}
			//update for user's voting
			$voteData->is_like = $vote;
          	$voteData->save();
         //else just increase total like or unlike
          }else{
          	
          	$row = $table->createRow();
            $row->country_id = $country_id;
            $row->voteoption_id = $option; 
            if($vote){
          		$row->total_like++;
          	}else{
          		$row->total_unlike++;
          	}        
            $row->save();
            // add new row for 
              $newRow = $votetable->createRow();
	          $newRow->user_id = $user_id;
	          $newRow->country_id = $country_id;
	          $newRow->voteoption_id = $option;
	          $newRow->is_like = $vote;
	          $newRow->save();
          }			

    
          $db->commit();
        }
    
        catch( Exception $e )
        {
          $db->rollBack();
          throw $e;
        }
        
        $voteresults = $table->fetchRow($select);
       
        $data = array();
        $data[] = array(
          'total_like' => $voteresults->total_like,
          'total_unlike' => $voteresults->total_unlike,
        );
        return $this->_helper->json($data);
        $data = Zend_Json::encode($data);
        $this->getResponse()->setBody($data);
    }
    
    public function suggestManagerAction(){
        $country_id = $this->_getParam('country_id');
        $memberCountryT = Engine_Api::_()->getDbtable('countrymembers','country');
        $select = $memberCountryT->select()
                                 ->where('country_id = ?',$country_id);
        $userIds = array();
        $rows = $memberCountryT->fetchAll($select);
        
        $userIds[0] = 0;
        foreach($rows as $row ){
            $userIds[] = $row->user_id;
        }
        
            
        $userTable = Engine_Api::_()->getDbtable('users','user');
        $select = $userTable->select()
                            ->where('user_id in (?)',$userIds);
        $users = $userTable->fetchAll($select);
        $data = array();
        foreach($users as $friend ) {
            $data[] = array(
              'type'  => 'user',
              'id'    => $friend->getIdentity(),
              'guid'  => $friend->getGuid(),
              'label' => $friend->getTitle(),
              'photo' => $this->view->itemPhoto($friend, 'thumb.icon'),
              'url'   => $friend->getHref(),
            );
            
        }
        return $this->_helper->json($data);
    }
    
    
    
  public function inviteAction()
  {
    // Render
    $this->_helper->content
        //->setNoRender()
        ->setEnabled()
        ;
    
    $settings = Engine_Api::_()->getApi('settings', 'core');

    // Check if admins only
    if( $settings->getSetting('user.signup.inviteonly') == 1 ) {
      if( !$this->_helper->requireAdmin()->isValid() ) {
        return;
      }
    }

    // Check for users only
    if( !$this->_helper->requireUser()->isValid() ) {
      return;
    }

    // Make form
    $this->view->form = $form = new Invite_Form_Invite();

    if( !$this->getRequest()->isPost() ) {
      return;
    }

    if( !$form->isValid($this->getRequest()->getPost()) ) {
      return;
    }

    $country_id = $this->_getParam('country_id',0);
    $this->view->country_id = $country_id;
    // Process
    $values = $form->getValues();
    $viewer = Engine_Api::_()->user()->getViewer();
    $inviteTable = Engine_Api::_()->getDbtable('invites', 'country');
    $db = $inviteTable->getAdapter();
    $db->beginTransaction();
    
    try {

      $emailsSent = $inviteTable->sendInvites($viewer, $values['recipients'], @$values['message'],$country_id);

      $db->commit();
    } catch( Exception $e ) {
      $db->rollBack();
      if( APPLICATION_ENV == 'development' ) {
        throw $e;
      }
    }

    //$this->view->alreadyMembers = $alreadyMembers;
    $this->view->emails_sent = $emailsSent;
    
    return $this->render('sent');
  }
    
}
